<template>
  <div class="app-container">
    <FilterSearch class="filter-search" :value="queryParams" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }"
      :config="configData" labelWidth="90px" position="right"></FilterSearch>
    <div class="main">
      <div class="table">
        <el-table stripe @selection-change="tableChange" :data="tableData.rows" border v-loading="tableData.loading"
          style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="id" width="60">
          </el-table-column>
          <el-table-column prop="taskName" label="任务名称" min-width="200">
          </el-table-column>
          <el-table-column prop="taskType" label="任务类型" min-width="100">
            <template v-slot="scope">
              <div v-for="(item, index) in taskType">
                <el-tag :type="item.type" v-if="item.value == scope.row.taskType">
                  {{ item.label }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="taskStatus" label="任务状态" width="80">
            <template v-slot="scope">
              <div v-for="(item, index) in taskStatus">
                <el-tag :type="item.type" v-if="item.value == scope.row.taskStatus">
                  {{ item.label }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="160">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.startTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="160">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.endTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="intervalTime" label="间隔时间" />
          <el-table-column prop="uid" label="创建人" />
          <el-table-column prop="createdTime" label="创建时间" width="160">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.createdTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="修改时间" width="160">
            <template v-slot="scope">
              <div>
                {{ getDate(scope.row.updateTime) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="240">
            <template v-slot="scope">
              <el-button @click="handleClick(scope.row, 'update')" type="text" size="small">编辑</el-button>
              <el-button @click="handleClick(scope.row, 'copy')" type="text" size="small">复制</el-button>
              <el-button @click="handleClick(scope.row, 'console')" type="text" size="small">控制台</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination @current-change="currentChange" layout="total, prev, pager, next, jumper" :total="tableData.total"
          :current-page="queryParams.currentPage" :page-size="queryParams.size">
        </el-pagination>
      </div>
    </div>
    <el-dialog v-model="rowData.diaVis" title="数据测试任务" :close-on-click-modal="false" :show-close="false" width="900px">
      <div class="box-container">
        <el-form label-position="left" label-width="160px" :model="rowData.formInline" ref="formState" :rules="rules">
          <el-form-item label="请定义任务名称:" prop="taskName">
            <el-input @change="taskNameRules" v-model="rowData.formInline.taskName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="请选择测试任务类型:" prop="taskType">
            <el-radio-group v-model="rowData.formInline.taskType" class="ml-4">
              <el-radio :label="1" size="large">规范性测试</el-radio>
              <el-radio :label="2" size="large">适应性测试</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="请选择算法模型:" prop="algorList">
            <div class="col">
              <div class="btn2" @click="handleClick({}, 'diaVis2')">
                <el-icon>
                  <Setting />
                </el-icon>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="执行开始时间:" prop="startTime">
            <el-date-picker style="width:100%;" :disabled-date="pickerOptions" v-model="rowData.formInline.startTime"
              @change="selStart" type="datetime" format="YYYY/MM/DD HH:mm:ss" placeholder="请选择开始时间" />
          </el-form-item>
          <el-form-item label="抽数间隔时间:" prop="intervalTime">
            <el-input v-model="rowData.formInline.intervalTime"
              @input="rowData.formInline.intervalTime = rowData.formInline.intervalTime.replace(/[^0-9.]/g, '')"
              placeholder="请输入抽数间隔时间(毫秒)" />
          </el-form-item>
          <el-form-item label="执行结束时间:" prop="endTime">
            <el-date-picker style="width:100%;" :disabled-date="pickerOptions" v-model="rowData.formInline.endTime"
              type="datetime" format="YYYY/MM/DD HH:mm:ss" @change="selEnd" placeholder="请选择结束时间" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(0)">取消</el-button>
          <el-button type="primary" @click="submit(0)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="rowData.diaVis2" width="60%" title="选择算法模型" :close-on-click-modal="false" :show-close="false">
      <div>
        <AlgorTable ref="algorTable"></AlgorTable>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(1)">取消</el-button>
          <el-button type="primary" @click="submit(1)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { ref, reactive, computed, onBeforeMount, onBeforeUnmount } from "vue"
import { useRouter } from 'vue-router';
import {
  getList, insertTask, selectByIds, selectOne, updateTask, delateTask
  , insertRules
} from "@/api/taskRunner.js"
import { formatDate } from "../../utils/index.js"
import AlgorTable from "@/components/AlgorTable/index.vue"
import { formData } from "@/utils/validate.js"
export default {
  components: {
    AlgorTable
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    const tableData = reactive({
      rows: [
        {
          id: 1,
          name: 'testTask1',
          sqlContent: "function testTask(){}",
          class: "three-zero-20",
          tel: 13345456785,
          createTime: "2023/11/04 15:08:09"
        },
        {
          id: 2,
          name: 'testTask2',
          sqlContent: "function testTask(){}",
          class: "three-zero-20",
          tel: 13323455678,
          createTime: "2023/11/04 15:08:09"
        },
        {
          id: 3,
          name: 'testTask3',
          sqlContent: "function testTask(){}",
          class: "three-zero-20",
          tel: 14576895648,
          createTime: "2023/11/04 15:08:09"
        }
      ],
      total: 0,
      loading: false,
      selection: []
    });

    const queryParams = ref({
      currentPage: 1,
      size: 10,
      taskName: "",
      taskStatus: null
    });
    const timeOut = {
      setTime1: null,
      setTime2: null,
      setTime3: null,
      setTime4: null,
      setTime5: null,
      setTime6: null,
    }
    const taskStatus = ref(
      [
        {
          label: "初始化",
          value: 1,
          type: ''
        },
        {
          label: "执行中",
          value: 2,
          type: 'warning'
        },
        {
          label: "已完成",
          value: 3,
          type: 'success'
        },
        {
          label: "异常",
          value: 4,
          type: 'danger'
        }
      ]
    )
    const taskType = ref(
      [
        {
          label: "规划性测试",
          value: 1,
          type: ''
        },
        {
          label: "适应性测试",
          value: 2,
          type: 'warning'
        },
        {
          label: "已完成",
          value: 3,
          type: 'success'
        },
        {
          label: "异常",
          value: 4,
          type: 'danger'
        }
      ]
    )
    const configData = computed(() => {
      let config = {
        itemConfig: [
          {
            type: "input",
            prop: "taskName",
            clearable: "关闭",
            label: "任务名称",
            placeholder: "请输入",
          },
          {
            type: "select",
            prop: "taskStatus",
            clearable: "关闭",
            label: "任务状态",
            placeholder: "请输入",
            optList: proxy.taskStatus
          }
        ],
        operate: [
          {
            icon: "Search",
            type: "primary",
            name: "查询",
            handleClick: getLoad,
            rule: true,
          },
          {
            icon: "RefreshLeft",
            type: "primary",
            name: "重置",
            handleClick: reset,
            rule: true,
          },
          {
            icon: "Plus",
            type: "primary",
            name: "新增",
            handleClick: insert,
            rule: true,
          },
          {
            icon: "Delete",
            type: "primary",
            name: "批量删除",
            handleClick: allDel,
            rule: true,
          }
        ],
        rules: {},
      };
      return config;
    })

    const validateTaskName = (rule, value, callback) => {
      if (proxy.rowData.taskNameStatus) {
        callback(new Error("测试任务名称已重复,请修改"));
      } else {
        callback();
      }
    };
    const rules = computed(() => {
      let rules = {
        taskName: [
          { required: true, trigger: "blur", message: "请输入任务名称" },
          { required: true, trigger: "change", message: "请输入任务名称" },
          {
            validator: validateTaskName,
            trigger: "change",
          },
          {
            validator: validateTaskName,
            trigger: "blur",
          },
        ],
        taskType: [
          { required: true, trigger: "blur", message: "请选择任务类型" },
          { required: true, trigger: "change", message: "请选择任务类型" },
        ],
        algorList: [
          { required: true, trigger: "blur", message: "请选择算法模型" },
          { required: true, trigger: "change", message: "请选择算法模型" },
        ],
        startTime: [
          { required: true, trigger: "blur", message: "请选择执行开始时间" },
          { required: true, trigger: "change", message: "请选择执行开始时间" },
        ],
        endTime: [
          { required: true, trigger: "blur", message: "请选择执行结束时间" },
          { required: true, trigger: "change", message: "请选择执行结束时间" },
        ],
        intervalTime: [
          { required: true, trigger: "blur", message: "请输入执行间隔" },
          { required: true, trigger: "change", message: "请输入执行间隔" },
        ]
      };
      return rules;
    })
    const rowData = reactive({
      diaVis: false,
      diaVis2: false,
      formInline: {
        algorList: [],
        taskType: 1
      },
      taskNameStatus: false
    })

    const pickerOptions = (time) => {
      const date = new Date();
      return time.getTime() <= date.getTime() - 8.64e7
    }
    const getDate = (date) => {
      return formatDate(date)
    }
    const currentChange = (currentPage) => {
      proxy.queryParams.currentPage = currentPage;
      getLoad();
    }
    const tableChange = (selection) => {
      proxy.tableData.selection = selection;
    }
    const taskNameRules = () => {
      insertRules(proxy.rowData.formInline.taskName).then(res => {
        if (res.data) {
          proxy.rowData.taskNameStatus = true;
        } else {
          proxy.rowData.taskNameStatus = false;
        }
        timeOut.setTime1 = setTimeout(() => {
          proxy.$refs.formState.validateField("taskName");
        }, 100);
      })
    }
    const selStart = (row) => {
      let today = new Date().getTime() - 8.64e7;
      let startTime = proxy.rowData.formInline.startTime.getTime();

      if (proxy.rowData.formInline.endTime) {
        let endTime = proxy.rowData.formInline.endTime.getTime();
        if (startTime >= endTime) {
          ElMessage.info('请选择小于结束时间的开始时间');
          proxy.rowData.formInline.startTime = null;
        }
        return;
      }
      if (today > startTime) {
        ElMessage.info('请选择未发生的时间');
        proxy.rowData.formInline.startTime = null;
      }
    }
    const selEnd = () => {
      let today = new Date().getTime() - 8.64e7;
      let endTime = proxy.rowData.formInline.endTime.getTime();
      if (proxy.rowData.formInline.startTime) {
        let startTime = proxy.rowData.formInline.startTime.getTime();
        if (startTime >= endTime) {
          ElMessage.info('请选择大于开始时间的结束时间');
          proxy.rowData.formInline.endTime = null;
        }
        return;
      }
      if (today > endTime) {
        ElMessage.info('请选择未发生的时间');
        proxy.rowData.formInline.endTime = null;
      }
    }
    const handleClick = (row, type) => {
      switch (type) {
        case 'diaVis2':
          proxy.rowData.diaVis2 = true;
          timeOut.setTime2 = setTimeout(() => {
            if (proxy.rowData.status == 1 || proxy.rowData.formInline.algorIds) {
              selectByIds(proxy.rowData.formInline.algorIds).then(res => {
                proxy.$refs.algorTable.changeData.rows = res.data;
                setTimeout(() => {
                  proxy.$refs.algorTable.checkStatus();
                }, 50);
              })
            }

          }, 100);
          break;
        case 'update':
          selectOne(row).then(res => {
            proxy.rowData.formInline = res.data;
            proxy.rowData.formTit = "编辑测试任务";
            proxy.rowData.diaVis = true;
            proxy.rowData.status = 1;
            selectByIds(proxy.rowData.formInline.algorIds).then(res => {
              proxy.rowData.formInline.algorList = res.data;
            })
          })
          break;
        case 'copy':
          selectOne(row).then(res => {
            proxy.rowData.formInline = res.data;
            proxy.rowData.formInline.id = null;
            proxy.rowData.formInline.taskName = "";
            proxy.rowData.formInline.startTime = null;
            proxy.rowData.formInline.endTime = null;

            proxy.rowData.formTit = "复制测试任务";
            proxy.rowData.diaVis = true;
            proxy.rowData.status = 0;
            selectByIds(proxy.rowData.formInline.algorIds).then(res => {
              proxy.rowData.formInline.algorList = res.data;
            })
          })
          break;
        case 'console':
          router.push({
            name: "media",
            params: {
              algorIds: row.algorIds,
              id: row.id,
              startTime: row.startTime,
              endTime: row.endTime,
              intervalTime: row.intervalTime,
            }
          });
          break;
        default:
          break;
      }
    }
    const getLoad = () => {
      proxy.tableData.loading = true;
      getList(proxy.queryParams).then(res => {
        proxy.tableData.loading = false;
        if (res.status == 'success') {
          ElMessage.success('查询成功');
        } else {
          ElMessage.error('查询失败');
          return;
        }
        proxy.tableData.rows = res.data.records;
        proxy.tableData.total = res.data.total;
      })
    }
    const insert = () => {
      proxy.rowData.diaVis = true;
      proxy.rowData.status = 0;
      proxy.rowData.formInline = {
        algorList: [],
        taskType: 1
      }
    }

    const submit = (type) => {
      switch (type) {
        case 0:
          proxy.$refs.formState.validate(valid => {
            if (valid) {
              if (proxy.rowData.status == 0) {
                insertTask(proxy.rowData.formInline).then(res => {
                  if (res.status == 'success') {
                    ElMessage.success(res.msg);
                    cancel(0);
                    getLoad();
                  } else {
                    ElMessage.error(res.msg);
                    return;
                  }
                })
              } else {
                updateTask(proxy.rowData.formInline).then(res => {
                  if (res.status == 'success') {
                    ElMessage.success(res.msg);
                    cancel(0);
                    getLoad();
                  } else {
                    ElMessage.error(res.msg);
                    return;
                  }
                })
              }
            }
          })
          break;
        case 1:
          let param = proxy.$refs.algorTable.changeData.rows;
          proxy.rowData.formInline.algorList = param;
          let ids = "";
          param.map(it => {
            ids += it.id + ',';
            return it.id;
          })
          ids = ids.slice(0, ids.length - 1);
          proxy.rowData.formInline.algorIds = ids;
          proxy.$refs.algorTable.cancel();
          timeOut.setTime3 = setTimeout(() => {
            proxy.rowData.diaVis2 = false;
          }, 100);
          break;
        default:
          break;
      }
    }
    const cancel = (type) => {
      switch (type) {
        case 0:
          proxy.rowData.formInline = {
            algorList: [],
            taskType: 1
          };
          timeOut.setTime4 = setTimeout(() => {
            proxy.$refs.formState.clearValidate();
            proxy.rowData.diaVis = false;
          }, 100);
          break;
        case 1:
          proxy.$refs.algorTable.cancel();
          timeOut.setTime5 = setTimeout(() => {
            proxy.rowData.diaVis2 = false;
          }, 100);
          break;
        default:
          proxy.rowData.formInline = {
            algorList: [],
            taskType: 1
          };
          proxy.$refs.algorTable.cancel();
          timeOut.setTime6 = setTimeout(() => {
            proxy.$refs.formState.clearValidate();
            proxy.rowData.diaVis = false;
            proxy.rowData.diaVis2 = false;
          }, 100);
          break;
      }
    }
    const reset = () => {
      proxy.rowData.diaVis = false;
      proxy.rowData.diaVis2 = false;
      proxy.rowData.formInline = {
        algorList: [],
        taskType: 1
      };
      proxy.rowData.formTit = "新增测试任务";
      proxy.rowData.status = 0;
      proxy.queryParams = {
        currentPage: 1,
        size: 10,
        taskName: "",
        taskStatus: null
      };
      getLoad();
    }
    const allDel = () => {
      if (proxy.tableData.selection.length <= 0) {
        ElMessage.info('请选择数据');
        return;
      }
      let ids = proxy.tableData.selection.map(it => {
        return it.id;
      })
      delateTask(formData({ ids })).then(res => {
        if (res.status == 'success') {
          ElMessage.success(res.msg);
          getLoad();
        } else {
          ElMessage.error('删除失败');
          return;
        }
      })
    }
    onBeforeMount(() => {
      getLoad();
    })

    onBeforeUnmount(() => {
      for (const key in timeOut) {
        if (timeOut[key]) {
          clearTimeout(timeOut[key]);
        }
      }
    })
    return {
      queryParams, configData, rowData, tableData, rules, taskStatus, pickerOptions,
      cancel, getDate, currentChange, tableChange, submit,
      handleClick, selStart, selEnd, taskNameRules, taskType
    }
  }
}


</script>
<style lang="scss" scoped>
$border-color: #c1c5cd;

.main {
  .page {
    padding: 10px 0;
    float: right;
  }
}

.box-container {
  .el-select {
    width: 100%;
  }

  .col {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;

    .btn2 {
      min-width: 50px;
      width: 50px;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      border-radius: 5px;
      border: solid 1px $border-color;
      padding: 0 5px;
      height: 32px;

      .txt {
        font-size: 12px;
      }

      &:hover {
        cursor: pointer;
      }
    }
  }

  .el-form {
    width: 100%;
  }
}

::v-deep .el-form-item__label {
  font-weight: 700;
}

::v-deep .el-date-editore {
  width: 100% !important;
}
</style>